Skip to content

使用 Visual Studio 發佈帶有預設檔案的 NuGet 套件

TLDR

  • 開發 NuGet 套件時,建議優先選擇 .NET Standard 作為目標平台。
  • 現代 .NET 專案可直接在 .csproj 中設定套件資訊,無需額外編寫 .nuspec 檔案。
  • 若需在安裝套件時自動複製設定檔,package.config 模式需搭配 install.ps1 腳本;PackageReference 模式則依賴專案檔中的 <Content> 設定。
  • .NET Framework 專案若使用 PackageReference,可能無法正確觸發檔案複製或 install.ps1 執行,建議針對此情境進行相容性測試。

開發套件前的基本知識

目標平台選擇

開發 NuGet 套件時,建議選擇 .NET Standard 以確保跨平台支援。若需支援舊版 .NET Framework,可在專案檔中設定 TargetFrameworks 進行多版本支援:

xml
<PropertyGroup>
  <TargetFrameworks>netstandard2.1;netstandard2.0;net45</TargetFrameworks>
</PropertyGroup>

編輯套件資訊

現代 Visual Studio 允許直接在 .csproj 檔案中定義 NuGet 套件的中繼資料(Metadata),取代了傳統的 .nuspec 檔案。關鍵設定如下:

  • Version: 建議遵循 SemVer 規範。
  • PackageLicenseExpression: 若使用 MIT 或 BSD 等常見授權,請使用 SPDX 授權識別碼
  • PackageId: 套件名稱,若未指定則預設使用專案名稱。

發佈帶有檔案的 NuGet 套件

在套件中包含預設設定檔(如 Config.json)時,需考量安裝套件的兩種主要格式:package.configPackageReference

檔案配置方式

若要讓套件包含檔案並在安裝時處理,請在 .csproj 中進行以下設定:

xml
<ItemGroup>
  <Content Include=".\Config.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <PackageCopyToOutput>true</PackageCopyToOutput>
  </Content>
  <None Include=".\install.ps1">
    <Pack>True</Pack>
    <PackagePath>tools</PackagePath>
  </None>
</ItemGroup>

install.ps1 的用途

什麼情況下會遇到這個問題:當您使用 package.config 格式安裝套件,且希望自動設定檔案屬性(如 Build Action 或 Copy to Output Directory)時。

此腳本僅對 package.config 有效,範例如下:

shell
param($installPath, $toolsPath, $package, $project)

# 設定檔案名稱
$configItem = $project.ProjectItems.Item("Config.json")

# 設定 'Copy To Output Directory' 為 PreserveNewest (2)
$copyToOutput = $configItem.Properties.Item("CopyToOutputDirectory")
$copyToOutput.Value = 2

# 設定 'Build Action' 為 Content (2)
$buildAction = $configItem.Properties.Item("BuildAction")
$buildAction.Value = 2

不同安裝情境的驗證結果

1. .NET Framework 搭配 package.config

  • 結果:成功。install.ps1 會自動執行,檔案屬性會被正確設定為「內容」與「有更新才複製」。

2. ASP.NET Core (使用 PackageReference)

  • 結果:部分成功。install.ps1 不會執行,但檔案會被加入專案,且複製屬性通常能正常運作。

3. .NET Framework 搭配 PackageReference

  • 結果:失敗。此組合不會執行 install.ps1,且檔案通常不會自動複製到目標專案中。
  • 建議:若您的套件必須支援此情境,建議在說明文件中提醒使用者手動加入設定檔,或考慮提供初始化程式碼而非依賴自動複製。

WARNING

NuGet.org 只接受開放原始碼方案或免費軟體基礎核准的授權運算式。


異動歷程

    • 初版文件建立。